package com.cyh.exp.controller;

import com.cyh.exp.mode.ResultCode;
import com.cyh.exp.mode.UploadFileProperties;
import com.cyh.exp.mode.UploadResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@RestController
public class FileUploadController {

    private UploadFileProperties uploadFileProperties;

    @Autowired
    public void setUploadFileProperties(UploadFileProperties uploadFileProperties){
        this.uploadFileProperties=uploadFileProperties;
    }
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy"+ File.separator+"MM"+File.separator+"dd");

    @PostMapping("/demo/upload")
    public UploadResult upload(@RequestParam(value = "file") MultipartFile[] uploadFiles,
                               HttpServletRequest req){

        String realPath = uploadFileProperties.getMultipart().getLocation()+File.separator+uploadFileProperties.getUploadFileDirectory();
        String format = sdf.format(new Date());
        File folder = new File(realPath+File.separator+format);
        if (!folder.isDirectory())
            folder.mkdir();
        String filePath = "";
        UploadResult result = null;
        for (MultipartFile file:uploadFiles){
            String oldName = file.getOriginalFilename();
            String newName = UUID.randomUUID().toString()+oldName.substring(oldName.lastIndexOf("."),oldName.length());
            try {
                file.transferTo(new File(folder,newName));
                String newPath = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+"/"+uploadFileProperties.getUploadFileDirectory()+"/"+format+"/"+newName;
                filePath += newPath + "\n";
            }
            catch (Exception e){
                e.printStackTrace();
                filePath = "上传失败";
                result = new UploadResult(ResultCode.ERROR.getCode(),"上传失败","");
            }
        }
        if (result == null)
            return new UploadResult(ResultCode.SUCCESS.getCode(), "上传成功",filePath);
        else return result;
    }
}
